<?php

class Core_Backend_Component_Permission_Controller_Accredit_Action extends Dcmp_Component_Controller {

    public function indexAction($pageindex = 1, $pagesize = 20, $areaid = 0) {
        $this->getHistory()->record();
        $collection = App::getModel('permission/collection_accredit_action')
                        ->filterByArea($this->getSession()->get('managed_area_id'))
                        ->asc('component_name')
                        ->asc('controller_name')
                        ->pagination($pageindex, $pagesize)
                        ->load();
        $records = $collection->loadCount();
        return $this->viewResult(array('list' => $collection, 'records' => $records));
    }

    public function createAction($areaid) {
        $roles = App::getModel('permission/collection_role')->filterByArea($areaid)->load();
        $area = App::getModel('global/area')->load($areaid);
        return $this->viewResult(array('area' => $area, 'roles'=>$roles));
    }

    public function editAction($id = NULL) {
        $model = App::getModel('permission/accredit_action')->load($id);
        return $this->createAction($model->getAreaId())->setModel($model);
    }

    public function deleteAction() {
        $ids = $this->getRequest()->getForm('ids');
        App::getModel('permission/accredit_action')->getTable()->deleteBatch($ids);
        return $this->redirectResult($this->getUrl($this->getRequest()->getMultiForm('pagesize')), 'index');
    }

    public function applyPostAction() {
        return $this->savePostAction(FALSE);
    }

    public function savePostAction() {
        return $this->saveModel();
    }

    private function saveModel($return = TRUE) {
        $data = $this->getRequest()->getForm('accredit');

        $model = App::getModel('permission/accredit_action');
        if (isset($data['id']) && !empty($data['id'])) {
            $model->load($data['id']);
        }
        $model->addData($data);
        if (($errors = $model->validate()) === TRUE) {
            $model->save();
            $this->getMessager()->addInform($this->__('share.message.success'));
            return $this->getRequest()->getForm('apply', FALSE) ?
                    $this->redirectResult($this->getUrl(array('id' => $model->getIdValue()), 'edit')) :
                    $this->redirectResult($this->getHistoryUrl('permission/accredit_action/index'));
        } else {
            $this->getMessager()->addError($this->__('share.message.fail'))
                    ->addError($errors);
            return $this->createAction()->setModel($model);
        }
    }

}